import axios, { AxiosInstance, AxiosRequestConfig } from "axios";

export function createAxiosByInterceptors(
  config?: AxiosRequestConfig
): AxiosInstance {
  const instance = axios.create({
    timeout: 10000,
    withCredentials: true,
    ...config
  });
  instance.interceptors.request.use(
    function(config: any) {
      console.log(`config: ${config}`);
      return config;
    },
    function(error) {
      // 对请求错误做些什么
      return Promise.reject(error);
    }
  );
  instance.interceptors.response.use(
    function(response) {
      console.log(`response: ${response}`);
      const { status, data } = response;
        if (status == 200) return data;
        else return Promise.reject(response);
      },
    function(error) {
      // 对响应错误做点什么
      console.error("error.response:", error.response);
      console.error("error.config:", error.config);
      console.error("error.request:", error.request);
      return Promise.reject(error)
    }
  );
  return instance;
}